<?php
/**
 * Bootstrap.php
 *
 * @copyright  2024 beikeshop.com - All Rights Reserved
 * @link       https://beikeshop.com
 * @author      <guangda.work>
 * @created    2024-05-14 15:15:27
 * @modified   2024-05-14 15:15:27
 */

namespace Plugin\GdRandomProducts;
use Beike\Repositories\ProductRepo;
use Beike\Shop\Http\Resources\ProductSimple;

class Bootstrap
{
    public function boot(): void
    {
        /**
         * Add module for admin design.
         */
        add_hook_filter('admin.design.index.data', function ($data) {
            $data['editors'][] = 'editor-random_products';

            return $data;
        });

        add_hook_filter('service.design.module.content', function ($data) {
            $module = $data['module_code'] ?? '';

            if ($module == 'random_products') {
                $data = self::handleProducts($data);
            }

            return $data;
        });
    }

    /**
     * 处理商品模块
     *
     * @param $content
     * @return array
     * @throws \Exception
     */
    private static function handleProducts($content): array
    {
        $type = $content['type'] ?? '';
        $value = $content['content'] ?? '';
        $quantity = $content['quantity'] ?? 0;

        $products = collect();
        if ($type == 'category' && $value) {
            $products = ProductRepo::getBuilder(['category_id' => $value])->get();
        }

        if ($type == 'brand' && $value) {
            $products = ProductRepo::getBuilder(['brand_id' => $value])->get();
        }

        if ($type == 'all') {
            $products = ProductRepo::getBuilder()->get();
        }

        if ($products->count() >= $quantity) {
            $products = $products->random($quantity);
        } else {
            $products = $products->shuffle(); // 少于目标数量，就随机打乱返回全部
        }

        $content['products'] = ProductSimple::collection($products)->jsonSerialize();
        $content['title']    = $content['title'][locale()] ?? '';

        return $content;
    }
}
